package cn.org.rookie.jeesdp.authentication.service.impl;

import cn.org.rookie.jeesdp.core.po.Authority;
import cn.org.rookie.jeesdp.core.po.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class AuthentictionServiceImpl implements UserDetailsService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public User loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = jdbcTemplate.queryForObject(
                "select * from sys_user where username = ? or  email = ? or phone = ?",
                new BeanPropertyRowMapper<>(User.class),
                username, username, username
        );

        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        List<Authority> authorities = jdbcTemplate.query(
                "select * from sys_role where id in (select authority_id from sys_user_authority where user_id = ?)",
                new BeanPropertyRowMapper<>(Authority.class),
                user.getId()
        );
        user.setAuthorities(authorities);

        return user;
    }
}
